package com.imay.live.activity.dynamics;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.imay.base.helper.NetworkHelper;
import com.imay.live.R;
import com.imay.live.adapter.RepostAdapter;
import com.imay.live.fragment.dynamics.DynamicsParams;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.LocationHelper;
import com.imay.live.helper.UrlHelper;
import com.imay.live.manager.FamilyAccountManager;
import com.imay.live.manager.SensitiveWordFilterManager;
import com.imay.live.manager.UploadFileManager;
import com.imay.live.model.FamilyUserInfo;
import com.imay.live.model.FeedModel;
import com.imay.live.model.MenuItemModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.ResultCode;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;


/**
 * 发布及编辑页面
 * Created by chan on 2017/4/17.
 */
public class ReleaseActivity extends DynamicsFeedActivity implements View.OnClickListener {

    private int status;
    private String imagePath;
    private String videoPath;
    private FeedModel feedBean;

    private Context mContext;

    public static int MOVIE = 1;
    public static int IMAGE = 2;
    public static int MODIFY = 3;

    public static void startActivity(Activity context, String imagePath, String videoPath, FeedModel bean, int status, int requestCode) {
        Intent intent = new Intent(context, ReleaseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("status", status);
        bundle.putString("imagePath", imagePath);
        bundle.putString("videoPath", videoPath);
        bundle.putParcelable("feedBean", bean);
        intent.putExtras(bundle);
        context.startActivityForResult(intent, requestCode);
    }

    public static void startActivity(Activity context, String imagePath, String videoPath, FeedModel bean, int status, boolean toast, int requestCode) {
        Intent intent = new Intent(context, ReleaseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("status", status);
        bundle.putString("imagePath", imagePath);
        bundle.putString("videoPath", videoPath);
        bundle.putParcelable("feedBean", bean);
        bundle.putBoolean("toaststatus", toast);
        intent.putExtras(bundle);
        context.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_release;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        com.imay.live.utils.ViewUtil.setForgroundRadius($(R.id.ll_content));
        mContext = this;
        feedStauts = STATUS_RELEASE;

        initDatas();
        initWidget();
        initListener();
    }

    /**
     * 初始化data
     */
    private void initDatas() {
        Bundle b = getIntent().getExtras();
        status = b.getInt("status");
        imagePath = b.getString("imagePath");
        videoPath = b.getString("videoPath");
        feedBean = b.getParcelable("feedBean");
        toaststatus = b.getBoolean("toaststatus", true);
    }

    /**
     * 初始化view
     */
    private void initWidget() {
        if (status == MOVIE) { // 视频
            $(R.id.iv_release_content_ico).setVisibility(View.VISIBLE);
        } else if (status == IMAGE) { // 图片
            $(R.id.iv_release_content_ico).setVisibility(View.INVISIBLE);
        } else if (status == MODIFY) { // 编辑
            if (feedBean.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_VIDEO) { // 视频
                $(R.id.iv_release_content_ico).setVisibility(View.VISIBLE);
            } else if (feedBean.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_IMAGE) { // 图片
                $(R.id.iv_release_content_ico).setVisibility(View.INVISIBLE);
            }
        }

        setTitle("");

        setRightView();
        mEtContent = $(R.id.et_realse_content);
        mCountText = $(R.id.tv_release_content);
        if (feedBean == null) {
            GlideUtil.loadRectangleImage((ImageView) $(R.id.iv_release_img), imagePath, R.dimen.size_4dp, R.drawable.shape_placeholder_2);
            mEtContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(count)});
            mCountText.setText(count + "");
        } else {
            if (feedBean.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_VIDEO) {
                GlideUtil.loadRectangleImage((ImageView) $(R.id.iv_release_img), UrlHelper.getVideoThumbUrl(feedBean.getVideoUrl()), R.dimen.size_4dp, R.drawable.shape_placeholder_2);
            } else if (feedBean.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_IMAGE) {
                GlideUtil.loadRectangleImage((ImageView) $(R.id.iv_release_img), feedBean.getImgUrl(), R.dimen.size_4dp, R.drawable.shape_placeholder_2);
            }
            mEtContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(count)});
            String des = feedBean.getMsg();
            mEtContent.setText(des);
            mEtContent.setSelection(des.length());
            mCountText.setText(count - des.length() + "");
        }


        mRepostAt = $(R.id.iv_repost_at);
        mRepostJin = $(R.id.iv_repost_jin);
        tv_familyId_status = $(R.id.tv_familyId_status);

        if (status == MODIFY) {
            internalPublic = feedBean.getInternalPublic();
            familyId = feedBean.getFamilyId();

            if (familyId != 0 && internalPublic != 0) {
                tv_familyId_status.setText(R.string.str_feed_menu_family);
            } else {
                tv_familyId_status.setText(R.string.str_feed_menu_open);
            }
        }

        loadView = $(R.id.lv_release);
        loadView.setVisibility(View.GONE);

        mRecyclerView = $(R.id.rcv_release);
        WrapContentLinearLayoutManager layoutManager
                = new WrapContentLinearLayoutManager(mContext);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new RepostAdapter();
        mAdapter.bindToRecyclerView(mRecyclerView);
        mRecyclerView.setHasFixedSize(true);
    }

    /**
     * 监听
     */
    @Override
    protected void initListener() {
        super.initListener();
        mRightView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!NetworkHelper.getInstance().hasConnection()) {
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                    ErrorResult.toastError(mContext, ResultCode.CodeNetErrorAction);
                    return;
                }
                if (!SensitiveWordFilterManager.getInstance().hasSensitiveWord(mEtContent)) {
                    DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getString(R.string.str_realse_loading));
                    if (status == MOVIE) { // 发布视频
                        if (TextUtils.isEmpty(videoPath)) {
                            ToastUtil.show(ReleaseActivity.this, R.string.str_release_file);
                            return;
                        }
                        UploadFileManager.getInstance().uploadVideo(videoPath, uploadCallBack);
                    } else if (status == IMAGE) { // 发布图片
                        if (TextUtils.isEmpty(imagePath)) {
                            ToastUtil.show(ReleaseActivity.this, R.string.str_release_file);
                            return;
                        }
                        UploadFileManager.getInstance().uploadPic(imagePath, uploadCallBack);
                    } else if (status == MODIFY) { // 编辑
                        modify(feedBean.getFeedId());
                    }
                } else {
                    ToastUtil.show(mContext, R.string.sensitive_comment);
                }
            }
        });
    }

    private UploadFileManager.UploadCallBack uploadCallBack = new UploadFileManager.UploadCallBack() {
        @Override
        public void uploadSuccess(String fileUrl) {
            realse(fileUrl);
        }

        @Override
        public void uploadFailer(int errorCode, String errorMessage) {
            DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
            ToastUtil.showImg(mContext, getString(R.string.str_realse_send_upload_failer), R.mipmap.jiaohutishidaxia_3x, 200);
        }
    };

    /**
     * 发布动态
     *
     * @param resultUrl 七牛路径
     */
    private void realse(String resultUrl) {
        String msg = mEtContent.getText().toString();
        if (msg.length() > 100) {
            ToastUtil.show(mContext, R.string.str_dynamics_comment_note);
            return;
        }
        // 创建动态
        LocationHelper helper = LocationHelper.getInstance();
        if (status == MOVIE) {
            createFeed("", resultUrl, msg, helper.getCity(), Long.toString((long) (helper.getLongitude() * 1000000L)), Long.toString((long) (helper.getLatitude() * 1000000L)), 0, familyId);
        } else if (status == IMAGE) {
            createFeed(resultUrl, "", msg, helper.getCity(), Long.toString((long) (helper.getLongitude() * 1000000L)), Long.toString((long) (helper.getLatitude() * 1000000L)), 0, familyId);
        }
    }

    /**
     * 编辑动态
     *
     * @param feedId
     */
    private void modify(int feedId) {
        String msg = mEtContent.getText().toString();
        if (msg.length() > 100) {
            ToastUtil.show(mContext, R.string.str_dynamics_comment_note);
            return;
        }
        if (status == MODIFY) {
            modifyFeed(feedId, msg);
        }
    }
}
